package com.yc.project1.dao;

import com.yc.project1.bean.BankAccount;
import com.yc.project1.dao.BankDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zwei
 * @create 2024-07-31 19:28
 */
@Repository
public class BankDaoImpl implements BankDao {        //dao层面向接口开发 先写一个dao层接口 然后写实现类
    @Autowired
    private DataSource dataSource;  //数据源

    @Override
    public List<BankAccount> findAll() {
        List<BankAccount> list = new ArrayList<>();
        try (Connection con = dataSource.getConnection();
             PreparedStatement pstmt = con.prepareStatement("select * from bank")) {
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                BankAccount ba = new BankAccount();
                ba.setId(rs.getInt(1));
                ba.setBalance(rs.getDouble(2));
                list.add(ba);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public BankAccount findById(int id) {
        BankAccount ba = null;
        try (Connection con = dataSource.getConnection();
             PreparedStatement pstmt = con.prepareStatement("select * from bank where id=?")){
            pstmt.setInt(1,id);
            ResultSet rs=pstmt.executeQuery();
            while (rs.next()){
                ba=new BankAccount();
                ba.setId(rs.getInt(1));
                ba.setBalance(rs.getDouble(2));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ba;
    }

    @Override
    public void update(BankAccount account) {
        try (Connection con=dataSource.getConnection();
             PreparedStatement pstmt=con.prepareStatement("update bank set balance=? where id=?")){
            pstmt.setDouble(1,account.getBalance());
            pstmt.setInt(2,account.getId());
            pstmt.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
